import { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { connect } from "react-redux";
import { setLanguageAction, setTokenAction, getUserInfoActionPromise } from "../../redux/modules/auth/action"
import './index.scss'
import Card from '@mui/material/Card';
import * as Colors from '@brightlayer-ui/colors'; // 伊顿颜色
import i18n from '../../language'
import { useTranslation } from 'react-i18next'
import { Button, CircularProgress, Select, MenuItem, FormControl, InputLabel } from '@mui/material'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import MyTextField from "../../components/MyForm/MyTextField";
import api from '../../api'
import { home_path } from "../../utils/system/system";

const Login = (props) => {
  const navigate = useNavigate()
  const [loginForm] = useState({
    userName: '',
    password: ''
  })
  const { t } = useTranslation()
  const eatonLogo = require('../../assets/imgs/eaton-logo-small.png')
  // 设置语言
  const handleLanguageChange = (event) => {
    i18n.changeLanguage(event.target.value);
    props.setLanguageAction(event.target.value)
  }
  // 登录 校验
  const login = (values, actions) => {
    api.auth.login({ ...values }).then(async res => {
      props.setTokenAction(res.data && res.data.token ? res.data.token : '')
      await props.getUserInfoActionPromise()
      actions.setSubmitting(false)
      navigate(home_path)
    }).catch(err => {
      actions.setSubmitting(false)
      console.log(err)
    })
  }
  const formValidate = (values) => {
    const errors = {}
    if (!values.userName) {
      errors.userName = t('common.userNameEmpty')
    }
    if (!values.password) {
      errors.password = t('common.passwordEmpty')
    }
    return errors
  }
  const hasToken = useCallback(() => {
    if (props.token) {
      return navigate(home_path)
    }
    return false
  }, [])

  useEffect(() => {
    hasToken()
  }, []);
  return (
    <Card className="loginPage" style={{ background: props.theme === 'dark' ? Colors.darkBlack : Colors.blue['500'] }}>
      <Card className='containerCard'>
        <div className='containerCard-top'>
          <img src={eatonLogo} style={{ maxWidth: '250px', margin: '10px' }} alt="" />
          <div>
            <FormControl variant="filled" sx={{ m: 1, minWidth: 120 }}>
              <InputLabel id="languageInputLable">{t('system.language')}</InputLabel>
              <Select
                labelId="languageInputLable"
                value={props.language}
                onChange={handleLanguageChange}
              >
                <MenuItem value={'zhCN'}>简体中文</MenuItem>
                <MenuItem value={'enUS'}>EN</MenuItem>
              </Select>
            </FormControl>
          </div>
        </div>
        <div className="containerCard-form">
          <Formik initialValues={loginForm} onSubmit={(values, actions) => login(values, actions)} validate={(values) => formValidate(values)}>
            {({ isSubmitting }) => (
              <Form className='MyForm'>
                <div className="formItem">
                  <Field style={{width: '100%'}} name="userName" placeholder={t('common.enterUserName')} label={t('common.userName')} component={MyTextField} />
                  <ErrorMessage name="userName" component="div" className="errorsMsgComp" />
                </div>
                <div className="formItem">
                  <Field style={{width: '100%'}} name="password" placeholder={t('common.enterPassword')} label={t('common.password')} type="password" component={MyTextField} />
                  <ErrorMessage name="password" component="div" className="errorsMsgComp" />
                </div>
                <div style={{textAlign: 'right'}}>
                    <Button type="submit" variant="contained" disabled={isSubmitting}>
                      {isSubmitting ?
                      <CircularProgress
                      size={18}
                      sx={{
                        color: Colors.gray['400'],
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        marginTop: '-9px',
                        marginLeft: '-9px'
                      }}
                    /> :
                    undefined }{t('common.login')}</Button>
                </div>
              </Form>
            )}
          </Formik>
        </div>
      </Card>
    </Card>
  )
}
const mapStateToProps = (state) => state.auth;
export default connect(mapStateToProps, {
  setLanguageAction,
  setTokenAction,
  getUserInfoActionPromise
})(Login)
